package com.iflytek.jcy.supervise.clue.common.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import cn.hutool.core.lang.Assert;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.ExportHeadersFootersMode;
import com.aspose.words.HtmlSaveOptions;
import com.aspose.words.HtmlVersion;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * word 与 html 互转
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/7/22
 */
@Slf4j
public class AsposeUtil {

    public static byte[] toWord(String html, String extension) throws Exception {
        Assert.notBlank(html, "html内容不能为空");
        if (!StringUtils.equalsAnyIgnoreCase(extension, "doc", "docx")) {
            throw new IllegalArgumentException("不支持导出" + extension + ", 仅支持doc, docx");
        }

        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.insertHtml(html);


        int format = "doc".equalsIgnoreCase(extension) ? SaveFormat.DOC : SaveFormat.DOCX;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            doc.save(outputStream, SaveOptions.createSaveOptions(format));
            return outputStream.toByteArray();
        }
    }

    /** 使用破解版apose-words */
    public static String toHtml(InputStream inputStream) throws Exception {
        Document doc = new Document(inputStream);
        // Save the document into HTML.
        HtmlSaveOptions opts = new HtmlSaveOptions(SaveFormat.HTML);
        opts.setHtmlVersion(HtmlVersion.HTML_5);
        opts.setExportImagesAsBase64(true);
        opts.setExportPageMargins(false);
        opts.setExportHeadersFootersMode(ExportHeadersFootersMode.NONE);
        opts.setEncoding(StandardCharsets.UTF_8);
        opts.setExportRoundtripInformation(true);

        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            doc.save(stream, opts);
            return stream.toString();
        }
    }
}
